package com.tt.vtg.dao.entity;

import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.tt.vtg.utils.VtgUtils;

@Entity
@Table(name="T_USER")
public class User extends AbstractEntity {

	private static final long serialVersionUID = 5473273106544077903L;

	@Column(name="USERID", unique=true)
	private String userId;
	
	@Column(name="USERNAME")
	private String userName;
	
	@Column(name="PASSWORD")
	private String password;
	
	@Column(name="SALT")
	private String salt;
	
	@Column(name="EMAIL")
	private String email;
	
	@Column(name="CREATETIME")
	@DateTimeFormat(pattern="dd/MM/yyyy HH:mm:ss")
	@Temporal(TemporalType.TIMESTAMP)
	private Date createTime;
	
	@ManyToMany(fetch=FetchType.EAGER)
	@JoinTable(name="T_USER_ROLE",
				joinColumns=@JoinColumn(name="user_pk"),
				inverseJoinColumns=@JoinColumn(name="role_pk"))
	@JsonIgnore
	private Set<Role> roles = new HashSet<>();
	
	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public User setPassword(String password) {
		this.password = password;
		return this;
	}

	public String getSalt() {
		return salt;
	}

	public void setSalt(String salt) {
		this.salt = salt;
	}

	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	public User(){
		setCreateTime(new Date());
	}

	public Set<Role> getRoles() {
		return roles;
	}

	public void addRoles(Role... rs){
		Arrays.asList(rs).forEach(r -> roles.add(r));
	}
	
	public void setRoles(Set<Role> roles){
		this.roles = roles;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
	
	public void genSalt(){
		salt = VtgUtils.generateSalt();
	}
	
	public void encryptPassword(){
		if(StringUtils.hasText(password)){
			password = VtgUtils.encrypt(password + salt);
		}
	}
}